//
// StoreNuke.Net -  http://www.storenuke.net
// Copyright (c) 2005
// by Robert J Collins ( info@storenuke.net ) of WillowTree Software, Inc. ( http://www.willowtreesoftware.com )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Security;
using System.Web.UI.WebControls;
using StoreNuke.StarterKit.Commerce.Components;

namespace StoreNuke.StarterKit.Commerce.StoreControls
{
	/// <summary>
	///		Summary description for Register.
	/// </summary>
	public class Register : StoreControl
	{
		protected Label MyError;
		protected RequiredFieldValidator RequiredFieldValidator1;
		protected TextBox Email;
		protected RegularExpressionValidator RegularExpressionValidator1;
		protected RequiredFieldValidator RequiredFieldValidator2;
		protected TextBox Password;
		protected RequiredFieldValidator RequiredFieldValidator3;
		protected TextBox ConfirmPassword;
		protected RequiredFieldValidator RequiredFieldValidator4;
		protected CompareValidator CompareValidator1;
		protected TextBox firstName;
		protected RequiredFieldValidator RequiredFieldValidator5;
		protected TextBox lastName;
		protected Button RegisterBtn;
		protected Label lblFirstName;
		protected Label lblLastName;
		protected Label lblEmail;
		protected Label lblPassword;
		protected Label lblConfirmPassword;
		protected __AddressControl _AddressControl1;

		private void Page_Load(object sender, EventArgs e)
		{
			_AddressControl1.AttnTitle = "Address Description";
			if(! Page.IsPostBack){
				if (Context.User.Identity.Name == ""){
					_AddressControl1.Country = ConfigurationSettings.AppSettings["DefaultContry"];
					RegisterBtn.Text = "Register";
				}else{
					//Get profile information
					LoadCustomerInfo();
					RegisterBtn.Text = "Save Profile";
				}
			}
		}

		private void LoadCustomerInfo()
		{
			// Create CustomerDetails Struct
			CustomerDetails myCustomerDetails = new CustomerDetails();
			CustomersDB accountSystem = new CustomersDB();
			SqlDataReader dr;
			myCustomerDetails = accountSystem.GetCustomerDetails(Context.User.Identity.Name);
			dr = accountSystem.GetPrimaryAddress(Convert.ToInt32(Context.User.Identity.Name));
			
			if(myCustomerDetails != null)
			{
				firstName.Text = myCustomerDetails.FirstName; 
				lastName.Text = myCustomerDetails.LastName; 
				Email.Text = myCustomerDetails.Email; 
				//Password.Text = Security.DecryptData(myCustomerDetails.Password);
			}

			if(dr.Read())
			{
				_AddressControl1.Address1 = dr["Address1"].ToString();
				_AddressControl1.Address2 = dr["Address2"].ToString();
				_AddressControl1.Attn = dr["Attn"].ToString();
				_AddressControl1.City = dr["City"].ToString();
				_AddressControl1.Region = dr["RegionCode"].ToString(); 
				_AddressControl1.Country = dr["CountryCode"].ToString(); 
				_AddressControl1.PostalCode = dr["PostalCode"].ToString();
				_AddressControl1.Phone1 = dr["Phone1"].ToString(); 
				_AddressControl1.Phone2 = dr["Phone2"].ToString();
			}
			dr.Close();

			//Disable Password Reqirement
			RequiredFieldValidator3.Enabled = false;
			RequiredFieldValidator4.Enabled = false;
		}

		//*******************************************************
		//
		// The RegisterBtn_Click event handler is used on this page to
		// add a new user into the Commerce Starter Kit Customers database.
		//
		// The event handler then migrates any items stored in the user's
		// temporary (non-persistent) shopping cart to their
		// permanent customer account, adds a cookie to the client
		// (so that we can personalize the home page's welcome
		// message), and then redirects the browser back to the
		// originating page.
		//
		//*******************************************************

		private void RegisterBtn_Click(object sender, EventArgs e) 
		{
			// Only attempt a login if all form fields on the page are valid
			if (Page.IsValid == true) 
			{

				// Store off old temporary shopping cart ID
				ShoppingCartDB shoppingCart = new ShoppingCartDB();
				String tempCartId = shoppingCart.GetShoppingCartId();

				// Add New Customer to CustomerDB database
				CustomersDB accountSystem = new CustomersDB();
				String customerId = Context.User.Identity.Name;

				if(customerId == "")
				{
					customerId = accountSystem.AddCustomer(firstName.Text, lastName.Text, Email.Text, Security.Encrypt(Password.Text),false);
					
					if(customerId != ""){
						AddAddress(customerId);

						// Set the user's authentication name to the customerId
						FormsAuthentication.SetAuthCookie(customerId, false);

						// Migrate any existing shopping cart items into the permanent shopping cart
						shoppingCart.MigrateCart(tempCartId, customerId);

						// Store the user's fullname in a cookie for personalization purposes
						Response.Cookies["ASPNETCommerce_FullName"].Value = Server.HtmlEncode(firstName.Text + " " + lastName.Text);

						// Redirect browser back to shopping cart page
						Response.Redirect("Default.aspx?scid=12");
					}
						else 
					{
						MyError.Text = "Registration failed:&nbsp; That email address is already registered.<br><img align=left height=1 width=92 src=images/1x1.gif>";
					}
				}
				else
				{
					if(accountSystem.UpdateCustomer(Convert.ToInt32(customerId), firstName.Text, lastName.Text, Email.Text, (Password.Text != "" ? Security.Encrypt(Password.Text) : Password.Text),IsStoreAdmin))
					{
						UpdateAddress(customerId);
						MyError.Text = "Profile Updated Successfully!";
					}
					else
					{
						MyError.Text = "Profile Update Failed!";
					}
				}
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.RegisterBtn.Click += new EventHandler(this.RegisterBtn_Click);
			this.Load += new EventHandler(this.Page_Load);

		}
		#endregion

		private void AddAddress(string id)
		{
			// Add New Customer to CustomerDB database
			CustomersDB accountSystem = new CustomersDB();
			accountSystem.AddCustomerAddress(Convert.ToInt32(id),
				_AddressControl1.Address1,
				_AddressControl1.Address2,
				_AddressControl1.Attn,
				_AddressControl1.City,
				_AddressControl1.Region, 
				_AddressControl1.Country, 
				_AddressControl1.PostalCode,
				_AddressControl1.Phone1, 
				_AddressControl1.Phone2, true);
		}

		private void UpdateAddress(string id)
		{
			// Add New Customer to CustomerDB database
			CustomersDB accountSystem = new CustomersDB();
			accountSystem.UpdatePrimaryCustomerAddress(Convert.ToInt32(id),
				_AddressControl1.Address1,
				_AddressControl1.Address2,
				_AddressControl1.Attn,
				_AddressControl1.City,
				_AddressControl1.Region, 
				_AddressControl1.Country, 
				_AddressControl1.PostalCode,
				_AddressControl1.Phone1, 
				_AddressControl1.Phone2);
		}
	}
}
